<?php 

namespace Api\Controller;

use Api\Event\Sso\ISso;
use Api\Event\UserEvent;
use Common\Util\ThinkSDK\ThinkOauth;
// +----------------------------------------------------------------------
// | 文件 SsoController.class.php
// +----------------------------------------------------------------------
// | 说明 第三方授权相关
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Author: 谢赤心 Legend. <xcx_legender@qq.com>
// +----------------------------------------------------------------------

class SsoController extends PublicController {

    /*
    {
{
display_name: "PDD韩服：河流之王塔姆辅助薇恩VS轮子妈！",
image: {
url: "http://vimg.dwstatic.com/1529/135791/9-220x124.jpg",
width: 200,
height: 200
},
author: {
display_name: "小学生院长",
url: "http://v.huya.com/u/5452110",
object_type: "person"
},
embed_code: "http://assets.dwstatic.com/video/vppp.swf?vid=135791&channelId=lol&auto_play=1&logo=huya&no_ad=1&from=weiboweb",
stream: {
url: "http://w5.dwstatic.com/2/6/1529/135791-99-1437014962.mp4",
hd_url: "http://w5.dwstatic.com/9/8/1529/135791-100-1437014962.mp4",
format: "mp4",
duration: 1241
},
summary: "　　PDD在韩服体验了一盘新英雄塔姆，不过话说PDD会玩辅助吗？",
url: "http://v.huya.com/play/135791.html",
links: {
url: "http://m.v.huya.com/play/135791.html?vfrom=weibowap",
scheme: "无",
display_name: "无"
},
tags: [
{
display_name: "河流之王塔姆肯奇视频"
}
],
create_at: "2015-07-16",
custom_data: {
source: "虎牙视频"
},
object_type: "video"
}
     */
    public function sinapi()
    {
        $url = I('url');
        $domain = C('LOCAL_DOMAIN');
        define('FLASH_URI', 'http://player.ucloud.com.cn/release/swf/ump_vod.swf');

        $matchPrefixList = [
            $domain.'/Home/share/video/id/',
            $domain.'/share/video/id/',
            $domain.'/video-',
        ];
        $id = 0;
        foreach ($matchPrefixList as $prefix) {
            if(startWith($url,$prefix)) {
                $id = substr($url, strlen($prefix));
                break;
            }
        }
        if (!$id) {
            $ret = [
                'errcode' => '-1',
                'msg'     => 'error',
            ];
            $this->ajaxReturn($ret);
        }

        $video = event('Video')->detail($id);

        // 默认取最低清晰度
        $dpi = end($video['dpi_levels']);
        $source_param = [
            'uri'  => $dpi['uri'],
            'from' => 'sina',
        ];
        I('appid') && $source_param['appid'] = I('appid');
        $source_url = $domain.'/api/video/source/id/'.$video['id'].'.mp4?'.urldecode(http_build_query($source_param));
        $ret = [
            'display_name' => $video['title'],
            'image' => [
                'url' => $video['thumb'],
                'width' => 480,
                'height' => 270,
            ],
            'author' => [
                'display_name' => $video['user']['nickname'],
                'url' => $domain.'/Home/others/index/uid/'.$video['uid'],
                'object_type' => 'person',
            ],
            'embed_code' => FLASH_URI.'?file='.urlencode($source_url),
            'stream' => [
                'url'    => $source_url,
                'hd_url' => $source_url,
                'format' => 'mp4',
                'duration' => (int)$video['time'],
            ],
            'summary' => $video['detail'] ?: $video['title'],
            'links'   => [
                'url'    => $url.'?vfrom=weibowap',
                'scheme' => '',
                'display_name' => '',
            ],
            'url'   => $url,
            'create_at' => date('Y-m-d', $video['create_time']),
            'custom_data' => ['source' => '66Play'],
            'object_type' => 'video'
        ];
        $this->ajaxReturn($ret);
        exit;
    }


    protected function sso_error()
    {
        return $this->error(self::$API_ERROR['SSO_LOGIN'], 'sso login error');
    }

    public function login()
    {
        $channel = I('channel');
        $code = I('code');
        if (!$channel ){
            return $this->param_error();
        }

        $sns = ThinkOauth::getInstance($channel);
        $extend = $sns->parseExtend(I(''));
        try {
            $open = $sns->getAccessToken($code, $extend);
        } catch (\Exception $e) {
            \Think\Log::record("[DEBUG: -- SSO ERR -- ]".$e->getMessage(), 'DEBUG');
            return $this->sso_error();
        }
        if(!$open){
            return $this->sso_error();
        }

        if ($channel == 'weixin'){
            $sns = ThinkOauth::getInstance($channel);
            $openid = $sns->getUnionid($open['access_token'], $open['openid']);
        }else{
            $openid = $open['openid'];
        }
        \Think\Log::record("[DEBUG] -- [OPENID] {$openid}", 'DEBUG');
        $uid = event('User')->ssoLogin($channel, $openid, $open['nickname'], ['avatar' => $open['avatar'], 'platform' => I('platform',0)]);
        if (!$uid){
            return $this->sso_error();
        }else{
            $Event = event('User');
            $res = event('User')->genToken($uid, '', 0, I('platform',0));
            if (empty($res['data']['nickname'])){
                $res['data']['refer_nickname'] = $open['nickname'];
            }
            event('Statis')->doLocalStatis('login', I('platform', 0));
            return $this->ajaxReturn($res);
        }
        return;
    }

    public function share_type()
    {
        $share_config = C('SHARE_CONFIG');
        $this->success('', json_decode($share_config, true));
    }
    public function share($type = '')
    {
        $this->checkLogin();

        $vid = I('id', 0, 'intval');
        if (empty($type) || empty($vid)) {
            $this->param_error();
        }
        $video = service('video')->find($vid);
        if (empty($video)) {
            $this->param_error();
        }
        uri_format($video['thumb']);
        $video['share_url'] = DOMAIN . "/Home/share/video/id/{$video['id']}?type=share";

        $sns = ThinkOauth::getInstance($type);
        $res = $sns->share($video);

        if (empty($res)) {
            $this->param_error();
        }

        $params = [
            'uid' => UID,
            'id'  => $video['id']
        ];
        event('LocalClient')->doRequest('video_share', $params);

        $this->success('', $res);
    }
}
